package com.butang.Filter;

import com.alibaba.fastjson.JSONObject;
import com.butang.pojo.Result;
import com.butang.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
/**
 * ClassName: LoginCheckFilter
 * Package: com.butang.controller
 * Description:
 *
 * @Author BuTang
 * @Create 2023/7/17 22:14
 * @Version 1.0
 */
@Slf4j
@WebFilter(urlPatterns = "/*" )//拦截所有请求
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //登录界面不需要拦截
        String s = request.getRequestURL().toString();
        if (s.contains("/login")) {
            log.info("进入”/login分支“");
            filterChain.doFilter(request, response);
            return;
        }

        //无token则拦截
        String token = request.getHeader("token");
//        if (token == null ) {
        if(!StringUtils.hasLength(token)){
            log.info("进入”无token则拦截“分支");

            Result notLogin = Result.error("NOT_LOGIN");
            String s1 = JSONObject.toJSONString(notLogin);

            //设置HTTP响应的内容类型和字符编码的方法。
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(s1);
            return;
        }


//        if(!StringUtils.hasLength(token)){
//            log.info("Token不存在");
//
//            Result responseResult = Result.errot("NOT_LOGIN");
//            //把Result对象转换为JSON格式字符串 (fastjson是阿里巴巴提供的用于实现对象和json的转换工具类)
//            String json = JSONObject.toJSONString(responseResult);
//            response.setContentType("application/json;charset=utf-8");
//            //响应
//            response.getWriter().write(json);
//
//            return;
//        }

        try {
            JwtUtils.parseJwt(token);
        } catch (Exception e) {
            log.info("令牌解析失败");
            Result notLogin = Result.error("NOT_LOGIN");
            String s1 = JSONObject.toJSONString(notLogin);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(s1);
//            throw new RuntimeException(e);
            return;
        }
        filterChain.doFilter(request, response);

    }
}
